package udp;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-11-23
 * Time：10:02
 */
public class EchoClient {
    private DatagramSocket socket = null;
    public EchoClient() throws SocketException {
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("input>  ");
            String request = scanner.nextLine();
            //1.构造发送的数据报
            DatagramPacket requestPacket = new DatagramPacket(
                    request.getBytes(StandardCharsets.UTF_8),
                    request.getBytes().length,
                    InetAddress.getByName("127.0.0.1") ,
                    30000);
            //2.发送数据报
            socket.send(requestPacket);
            //3.接收响应数据报
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            //4.解析响应
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.printf("request：%s，response：%s\n", request, response);
        }
    }

    public static void main(String[] args) throws IOException {
        EchoClient echoClient = new EchoClient();
        echoClient.start();
    }
}
